//Inicializacion de datePicker...
$(function() {
    //modal estudios
    $( "#inputFechaInicio" ).datepicker({changeMonth: true,changeYear: true});
    $( "#inputFechaTermino" ).datepicker({changeMonth: true,changeYear: true});
    $( "#inputFechaI" ).datepicker({changeMonth: true,changeYear: true});
    $( "#inputFechaT" ).datepicker({changeMonth: true,changeYear: true});
    $( "#inputFechaIni" ).datepicker({changeMonth: true,changeYear: true});
    $( "#inputFechaTer" ).datepicker({changeMonth: true,changeYear: true});

    //modal agregar aplicaciones
    $( "#fechaAplicacion" ).datepicker({changeMonth: true,changeYear: true});
    $( "#fechaInicio" ).datepicker({changeMonth: true,changeYear: true});
    $( "#fechaTermino" ).datepicker({changeMonth: true,changeYear: true});
    
    //Modal Previos
    $( "#fechaAppPrevio" ).datepicker({changeMonth: true,changeYear: true});
    $( "#fechaAppPrevio" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
    
    //Modal empresas
    $( "#fechaingreso" ).datepicker({changeMonth: true,changeYear: true});
    $( "#fechaingreso" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
    
    //clase dp..
    $( ".dp" ).datepicker( "option", "showAnim", "drop");
    $( ".dp" ).datepicker( "option", "dateFormat", "yy/mm/dd" );
    $( ".dp" ).datepicker( "option", "monthNamesShort", [ "Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic" ] );
    $( ".dp" ).datepicker( "option", "dayNamesMin", [ "Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa" ] );
    $( ".dp" ).datepicker( "option", "firstDay", 1 );
    
  });

/* Modificacion  de la paginación de Datatable para Bootstrap 3 */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
    return {
        "iStart":         oSettings._iDisplayStart,
        "iEnd":           oSettings.fnDisplayEnd(),
        "iLength":        oSettings._iDisplayLength,
        "iTotal":         oSettings.fnRecordsTotal(),
        "iFilteredTotal": oSettings.fnRecordsDisplay(),
        "iPage":          Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
        "iTotalPages":    Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
    };
}


$.extend( $.fn.dataTableExt.oPagination, {
    "bootstrap": {
        "fnInit": function( oSettings, nPaging, fnDraw ) {
                var oLang = oSettings.oLanguage.oPaginate;
                var fnClickHandler = function ( e ) {
                        e.preventDefault();
                        if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                                fnDraw( oSettings );
                        }
                };

                $(nPaging).addClass('pagination').append(
                        '<ul class="pagination">'+
                                '<li class="disabled"><a href="#">&laquo;</a></li>'+
                                '<li class="disabled"><a href="#">&raquo;</a></li>'+
                        '</ul>'
                );
                var els = $('a', nPaging);
                $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
                $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
        },

        "fnUpdate": function ( oSettings, fnDraw ) {
                var iListLength = 5;
                var oPaging = oSettings.oInstance.fnPagingInfo();
                var an = oSettings.aanFeatures.p;
                var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

                if ( oPaging.iTotalPages < iListLength) {
                        iStart = 1;
                        iEnd = oPaging.iTotalPages;
                }
                else if ( oPaging.iPage <= iHalf ) {
                        iStart = 1;
                        iEnd = iListLength;
                } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
                        iStart = oPaging.iTotalPages - iListLength + 1;
                        iEnd = oPaging.iTotalPages;
                } else {
                        iStart = oPaging.iPage - iHalf + 1;
                        iEnd = iStart + iListLength - 1;
                }

                for ( i=0, iLen=an.length ; i<iLen ; i++ ) {
                        // Remove the middle elements
                        $('li:gt(0)', an[i]).filter(':not(:last)').remove();

                        // Add the new list items and their event handlers
                        for ( j=iStart ; j<=iEnd ; j++ ) {
                                sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                                $('<li '+sClass+'><a href="#">'+j+'</a></li>')
                                        .insertBefore( $('li:last', an[i])[0] )
                                        .bind('click', function (e) {
                                                e.preventDefault();
                                                oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                                                fnDraw( oSettings );
                                        } );
                        }

                        // Add / remove disabled classes from the static elements
                        if ( oPaging.iPage === 0 ) {
                                $('li:first', an[i]).addClass('disabled');
                        } else {
                                $('li:first', an[i]).removeClass('disabled');
                        }

                        if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                                $('li:last', an[i]).addClass('disabled');
                        } else {
                                $('li:last', an[i]).removeClass('disabled');
                        }
                }
        }
    }
} );

  $.fn.reset = function () {
    $(this).each (function() { this.reset(); });
  }

  $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }; 

  function mensaje(titulo,texto){
      notice.pnotify({
        title: titulo,
        text: texto,
        icon: true,
        width: $.pnotify.defaults.width,
        hide: true,
        closer: true,
        sticker: true,
        type: 'success'
    });
  }  

function inicio(){
    setTimeout(function(){cargarEstados(2)},100);
    $('#cmbestados').change(cargarEstados);			
    initMap();
    $('#botonModal').text("Agregar");
    var ins = document.getElementById('modalClientes').getElementsByTagName('input');               
    for(var i=0; i<ins.length; i++)
       ins[i].value = "";

    document.getElementById("nombre").disabled = false;
    document.getElementById("rfc").disabled = false; 	
    document.getElementById("carpeta").disabled = false;
    document.getElementById('modalForm').action = window.location+"/agregar";        
         
}

//Carga las opciones del combo Estados        
function cargarEstados(ciudad){
   var cmbid = $('#cmbestados').val();
   $.getJSON('clientes/call_ciudades',{id: cmbid}, function(resp){
            $('#cmbciudades').empty();
            $.each(resp, function(indice, valor){
                    option = $('<option></option>',{
                                    value: indice, 
                                    text: valor                                                
                            });
                    $('#cmbciudades').append(option);
            });
            $('#cmbciudades').val(ciudad);
    });
}

function showNotify(titulo,mensaje,clase){
    $.pnotify({
            title: titulo,
            text: mensaje,
            addclass: clase,
            delay: 2000,
            icon: 'picon-'+clase,
            opacity: .9,
            speed:200,
            animation: {
                effect_in: 'drop',
                easing_in: 'easeOutBounce',
                effect_out: 'same',
                easing_out: 'easeOutCubic'
            },
            nonblock: true,
            nonblock_opacity: .2
        });
}


function  getConfiguracion(){
   $('#formconf')[0].reset();
   document.getElementById('error').style.visibility="hidden";
    $.ajax({
        type:"POST",
        url:"upload/configuracion",
        dataType:"html",
        data:"",
        async: false,
        beforeSend:function(){
        },
        success:function(data){           
            var data = JSON.parse(data);
            if(data.datos1!=""){
            document.getElementById('logo').src=data.img;
            document.getElementById('nombreempresa').innerHTML=data.datos1.empresa;
            var aux=data.datos1.subtitulo.split(",");
            var aux2=document.getElementsByName("campos[]");
            for (var i=0;i<aux2.length;i++){
               for (var j=0;j<aux.length;j++){
                   if(aux2[i].value==aux[j]){
                       aux2[i].checked=true;
                   }                
               } 
            }
            }else{
                document.getElementById('nombreempresa').innerHTML=data.empresa;
            }
        }
    });
}


function validarconfiguracion(){
    var dato=$('.checkboxc:checked');      
    $(".checkboxc")[0].setCustomValidity("");    
     if(dato.length == 0)         
       $(".checkboxc")[0].setCustomValidity("Seleccionar almenos un campo");
    
}

function handleFileSelect(evt) {
  var files = evt.target.files; // FileList object
    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }
      var reader = new FileReader();
      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
             var image = new Image();
            image.onload = function() {
                if(this.width > 200 ||  this.height >200){
                    document.getElementById('files').value='';
                    document.getElementById('logo').src='POSmobile.png';
                    document.getElementById('error').style.visibility="visible";
                }else{
                    document.getElementById('error').style.visibility="hidden";
                     document.getElementById('logo').src=e.target.result;
                }
            };
            image.onerror = function() {
                alert('Not a valid file type: ');
            };
              var url = window.URL || window.webkitURL;
              image.src = e.target.result;
          // Render thumbnail.
         /* var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);*/
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }
  


  document.getElementById('files').addEventListener('change', handleFileSelect, false);

